package com.asggo.g21.payload.lann;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.excel.util.ListUtils;
import com.anwen.mongo.mapper.MongoPlusMapMapper;
import com.asggo.g21.utils.RedisUtils;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.stream.Collectors;
import lombok.extern.slf4j.Slf4j;

/**
 * Created by IntelliJ IDEA.
 *
 * @author eric 2024/6/4 15:38
 */
@Slf4j
public class NoModelDataListener extends AnalysisEventListener<Map<Integer, Object>> {

  private final MongoPlusMapMapper mongoPlusMapMapper;

  public NoModelDataListener(MongoPlusMapMapper mongoPlusMapMapper) {
    this.mongoPlusMapMapper = mongoPlusMapMapper;
  }

  /**
   * 每隔5条存储数据库，实际使用中可以100条，然后清理list ，方便内存回收
   */
  private static final int BATCH_COUNT = 5000;
  private List<Map<String, Object>> cachedDataList = ListUtils.newArrayListWithExpectedSize(
      BATCH_COUNT);

  private final List<String> head = new ArrayList<>();

  @Override
  public void invokeHeadMap(Map<Integer, String> data, AnalysisContext context) {
    head.addAll(data.values());

    // 已经存在的表头
    final List<String> headList = RedisUtils.getCacheList("dp:head");
    merge(headList, head);

    RedisUtils.setCacheList("dp:head", headList);
  }

  private void merge(List<String> headList, List<String> head) {
    for (String s : head) {
      if (headList.contains(s)) {
        continue;
      }
      headList.add(s);
    }
  }

  @Override
  public void invoke(Map<Integer, Object> data, AnalysisContext context) {
    final Map<String, Object> collected = data.entrySet().stream()
        .filter(k -> k.getValue() != null)
        .collect(Collectors.toMap(k -> head.get(k.getKey()), Entry::getValue, (o, n) -> n,
            LinkedHashMap::new));
    cachedDataList.add(collected);

    if (cachedDataList.size() >= BATCH_COUNT) {
      saveData();
      cachedDataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);
    }
  }

  @Override
  public void doAfterAllAnalysed(AnalysisContext context) {
    saveData();
    log.info("所有数据解析完成！");
  }

  /**
   * 加上存储数据库
   */
  private void saveData() {
    log.info("{}条数据，开始存储数据库！", cachedDataList.size());
//    String keyPrefix = "DP:DATA:";
//    String idKey = "dp:id";
//    for (Map<String, Object> dataMap : cachedDataList) {
//      final Object id = dataMap.get("点评商户id");
//      String key = keyPrefix + id.toString();
//      final Map<String, Object> cacheMap = RedisUtils.getCacheMap(key);
//      // 合并2个map的数据
//      dataMap.putAll(cacheMap);
//
//      if (RedisUtils.cacheSetContains(idKey, id)) {
//        log.info("存在的id ->{}", id);
//      } else {
//        RedisUtils.setCacheSet(idKey, id);
//      }
//
//      RedisUtils.setCacheMap(key, dataMap);
//    }

    // mongoPlusMapMapper.saveBatch("dp", cachedDataList);

    log.info("存储数据库成功！");
  }
}
